<template>
  <div class="tomcat-list">
    <div class="operation-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索服务器名称/IP/端口"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        新增服务器
      </el-button>
    </div>

    <el-table :data="servers" style="width: 100%" v-loading="loading">
      <el-table-column prop="serverName" label="服务器名称" />
      <el-table-column prop="host" label="服务器IP" />
      <el-table-column prop="port" label="端口号" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'Running' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template #default="scope">
          <el-button 
            type="primary" 
            :loading="scope.row.restarting"
            @click="handleRestart(scope.row)"
          >
            重启
          </el-button>
          <el-button 
            type="success" 
            @click="handleFiles(scope.row)"
          >
            文件管理
          </el-button>
          <el-button 
            type="info" 
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑服务器' : '新增服务器'"
      width="50%"
    >
      <el-form :model="editingServer" label-width="120px">
        <el-form-item label="服务器名称" required>
          <el-input v-model="editingServer.serverName" />
        </el-form-item>
        <el-form-item label="服务器IP" required>
          <el-input v-model="editingServer.host" />
        </el-form-item>
        <el-form-item label="端口号" required>
          <el-input v-model="editingServer.port" />
        </el-form-item>
        <el-form-item label="Tomcat路径" required>
          <el-input v-model="editingServer.serverPath" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <p>确定要删除该服务器吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文件管理对话框 -->
    <el-dialog
      v-model="fileDialogVisible"
      title="文件管理"
      width="60%"
    >
      <div class="file-dialog-content">
        <div class="file-header">
          <div class="file-upload">
            <el-upload
              :action="uploadUrl"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="handleBeforeUpload"
              :headers="uploadHeaders"
              :show-file-list="false"
              :multiple="false"
            >
              <el-button type="primary">上传文件</el-button>
            </el-upload>
          </div>
          <el-input
            v-model="fileSearchQuery"
            placeholder="搜索文件名"
            class="search-input"
            clearable
            @input="handleFileSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <el-table :data="fileList" style="width: 100%" v-loading="fileLoading">
          <el-table-column prop="name" label="文件名" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button 
                type="primary" 
                link
                @click="handleDownload(scope.row)"
              >
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 文件列表分页器 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="fileCurrentPage"
            v-model:page-size="filePageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="fileTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleFileSizeChange"
            @current-change="handleFileCurrentChange"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 文件覆盖确认对话框 -->
    <el-dialog
      v-model="overwriteDialogVisible"
      title="文件已存在"
      width="30%"
    >
      <p>文件 "{{ fileToOverwrite?.name }}" 已存在，是否覆盖？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleOverwriteCancel">取消</el-button>
          <el-button type="primary" @click="handleOverwriteConfirm">确认覆盖</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'TomcatList',
  components: {
    Search
  },
  setup() {
    const servers = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const deleteDialogVisible = ref(false)
    const editingServer = ref({})
    const isEdit = ref(false)
    const serverToDelete = ref(null)
    const searchQuery = ref('')
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 文件管理相关
    const fileDialogVisible = ref(false)
    const fileList = ref([])
    const fileLoading = ref(false)
    const currentServer = ref(null)
    const fileSearchQuery = ref('')
    const fileCurrentPage = ref(1)
    const filePageSize = ref(50)  // 默认显示50条
    const fileTotal = ref(0)
    
    // 文件覆盖相关
    const overwriteDialogVisible = ref(false)
    const fileToOverwrite = ref(null)
    const uploadFile = ref(null)

    const fetchServers = async () => {
      try {
        loading.value = true
        const response = await axios.get('/api/tomcat/list', {
          params: {
            page: currentPage.value - 1,  // 后端从0开始计数
            size: pageSize.value,
            search: searchQuery.value
          }
        })
        if (response.data) {
          servers.value = response.data.content
          total.value = response.data.totalElements
        }
      } catch (error) {
        console.error('Error fetching servers:', error)
        ElMessage.error('获取服务器列表失败')
      } finally {
        loading.value = false
      }
    }

    // 使用防抖处理搜索
    let searchTimeout
    const handleSearch = () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
      searchTimeout = setTimeout(() => {
        currentPage.value = 1  // 重置到第一页
        fetchServers()
      }, 300)
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchServers()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchServers()
    }

    const handleAdd = () => {
      isEdit.value = false
      editingServer.value = {
        serverName: '',
        host: '',
        port: '',
        serverPath: ''
      }
      dialogVisible.value = true
    }

    const handleEdit = (server) => {
      isEdit.value = true
      editingServer.value = { ...server }
      dialogVisible.value = true
    }

    const handleDelete = (server) => {
      serverToDelete.value = server
      deleteDialogVisible.value = true
    }

    const confirmDelete = async () => {
      try {
        await axios.delete(`/api/tomcat/${serverToDelete.value.id}`)
        ElMessage.success('删除成功')
        deleteDialogVisible.value = false
        await fetchServers()
      } catch (error) {
        console.error('Delete error:', error)
        ElMessage.error('删除失败')
      }
    }

    const handleSave = async () => {
      try {
        if (isEdit.value) {
          await axios.put('/api/tomcat/update', editingServer.value)
        } else {
          await axios.post('/api/tomcat', editingServer.value)
        }
        ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        dialogVisible.value = false
        await fetchServers()
      } catch (error) {
        console.error('Save error:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      }
    }

    const handleRestart = async (server) => {
      try {
        server.restarting = true
        await axios.post(`/api/tomcat/restart/${server.id}`)
        ElMessage.success('重启命令已发送')
        await fetchServers()
      } catch (error) {
        console.error('Restart error:', error)
        ElMessage.error(error.response?.data || '重启失败')
      } finally {
        server.restarting = false
      }
    }

    const handleFiles = async (server) => {
      currentServer.value = server
      fileDialogVisible.value = true
      await loadFiles()
    }
    
    const loadFiles = async () => {
      if (!currentServer.value) return
      
      try {
        fileLoading.value = true
        const response = await axios.get(`/api/file/list/${currentServer.value.id}`, {
          params: {
            page: fileCurrentPage.value - 1,
            size: filePageSize.value,
            search: fileSearchQuery.value
          }
        })
        if (response.data) {
          fileList.value = response.data.content.map(name => ({ name }))
          fileTotal.value = response.data.totalElements
        }
      } catch (error) {
        console.error('Error loading files:', error)
        ElMessage.error('获取文件列表失败')
      } finally {
        fileLoading.value = false
      }
    }
    
    const handleBeforeUpload = async (file) => {
      // 添加文件类型和大小的验证
      const isValidType = file.name.toLowerCase().endsWith('.cpt')
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isValidType) {
        ElMessage.error('只能上传 .cpt 文件!')
        return false
      }
      if (!isLt50M) {
        ElMessage.error('文件大小不能超过 50MB!')
        return false
      }

      try {
        // 检查文件是否存在
        const response = await axios.get(`/api/file/exists/${currentServer.value.id}/${encodeURIComponent(file.name)}`)
        if (response.data) {
          // 文件存在，显示确认对话框
          fileToOverwrite.value = file
          uploadFile.value = file
          overwriteDialogVisible.value = true
          return false // 阻止自动上传
        }
        return true // 文件不存在，允许上传
      } catch (error) {
        console.error('Check file exists error:', error)
        ElMessage.error('检查文件是否存在时发生错误')
        return false
      }
    }
    
    const handleUploadSuccess = (response, file) => {
      ElMessage.success(`${file.name} 上传成功`)
      loadFiles()
    }
    
    const handleUploadError = (error, file) => {
      console.error('Upload error:', error)
      ElMessage.error(`${file.name} 上传失败: ${error.message || '未知错误'}`)
    }
    
    const handleDownload = async (file) => {
      try {
        const response = await axios.get(
          `/api/file/download/${currentServer.value.id}/${encodeURIComponent(file.name)}`,
          { responseType: 'blob' }
        )
        
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', file.name)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)  // 清理 URL 对象
      } catch (error) {
        console.error('Download error:', error)
        ElMessage.error('下载失败')
      }
    }
    
    const uploadUrl = computed(() => 
      currentServer.value ? `/api/file/upload/${currentServer.value.id}` : ''
    )
    
    const uploadHeaders = {
      // 如果需要，可以在这里添加认证头
    }

    // 使用防抖处理文件搜索
    let fileSearchTimeout
    const handleFileSearch = () => {
      if (fileSearchTimeout) {
        clearTimeout(fileSearchTimeout)
      }
      fileSearchTimeout = setTimeout(() => {
        fileCurrentPage.value = 1  // 重置到第一页
        loadFiles()
      }, 300)
    }

    const handleOverwriteConfirm = async () => {
      overwriteDialogVisible.value = false
      if (uploadFile.value) {
        const formData = new FormData()
        formData.append('file', uploadFile.value)
        await axios.post(`/api/file/overwrite/${currentServer.value.id}`, formData)
        loadFiles()
        ElMessage.success('文件覆盖成功')
      }
    }

    const handleOverwriteCancel = () => {
      overwriteDialogVisible.value = false
      uploadFile.value = null
    }

    const handleFileSizeChange = (val) => {
      filePageSize.value = val
      loadFiles()
    }

    const handleFileCurrentChange = (val) => {
      fileCurrentPage.value = val
      loadFiles()
    }

    onMounted(() => {
      fetchServers()
    })

    return {
      servers,
      loading,
      dialogVisible,
      deleteDialogVisible,
      editingServer,
      isEdit,
      serverToDelete,
      currentPage,
      pageSize,
      total,
      searchQuery,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      confirmDelete,
      handleSave,
      handleRestart,
      handleFiles,
      fileDialogVisible,
      fileList,
      fileLoading,
      currentServer,
      fileSearchQuery,
      fileCurrentPage,
      filePageSize,
      fileTotal,
      fileSearchQuery,
      handleFileSearch,
      loadFiles,
      uploadUrl,
      uploadHeaders,
      handleBeforeUpload,
      handleUploadSuccess,
      handleUploadError,
      handleDownload,
      handleOverwriteConfirm,
      handleOverwriteCancel,
      overwriteDialogVisible,
      fileToOverwrite,
      handleFileSizeChange,
      handleFileCurrentChange,
    }
  }
}
</script>

<style scoped>
.tomcat-list {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-button {
  margin-left: 8px;
}

.file-dialog-content {
  padding: 20px;
}

.file-upload {
  margin-bottom: 20px;
}

.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.file-upload {
  flex-shrink: 0;
}

.file-dialog-content .search-input {
  width: 300px;
  margin-left: 20px;
}
</style>